{% extends '__base__.html' %}

{% block title %}网盘{% endblock %}

{% block content %}
    <div class="container">
        <div class="row">
            <div class="btn-toolbar col-md-8" role="toolbar" aria-label="Toolbar with button groups">
              <div class="btn-group mr-2" role="group" aria-label="First group">
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#filezone">上传</button>
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#mkdir">新建文件夹</button>
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#offline">离线下载</button>
              </div>
              <div id="optfile" class="btn-group mr-2 collapse" role="group" aria-label="Second group">
                <button type="button" class="btn btn-primary download">下载</button>
                <button type="button" class="btn btn-primary showfile">预览</button>
                <button type="button" class="btn btn-primary move">移动</button>
                <button type="button" class="btn btn-primary rename">重命名</button>
              </div>
              <div id="optdir" class="btn-group mr-2 collapse" role="group" aria-label="Second group">
                <button type="button" class="btn btn-primary move">移动</button>
                <button type="button" class="btn btn-primary rename">重命名</button>
              </div>
            </div>
        </div>
        <div id="filezone" class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
            <div class="modal-content">
              <input id="fileElem" type="file" name="upload"  style="display:none">
              <label id="fileSelect" class="text-center">Select some files</label>
            </div>
          </div>
        </div>
        <div id="mkdir" class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
            <div class="modal-content">
              <div class="input-group">
                  <input type="text" class="form-control" placeholder="输入文件名" aria-label="Recipient's username" aria-describedby="basic-addon2">
                  <button class="btn btn-success input-group-append mkdir" data-path="/{{ path | join('/') }}">确定</button>
                </div>
            </div>
          </div>
        </div>
        <div id="offline" class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
            <div class="modal-content">
              <div class="input-group">
                  <input type="text" class="form-control" placeholder="输入URL" aria-label="Recipient's username" aria-describedby="basic-addon2">
                  <button class="btn btn-success input-group-append offline" data-path="/{{ path | join('/') }}">确定</button>
                </div>
            </div>
          </div>
        </div>
        <div id="rename" class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
            <div class="modal-content">
              <div class="input-group">
                  <input type="text" class="form-control" placeholder="输入新的文件名" aria-label="Recipient's username" aria-describedby="basic-addon2">
                  <button class="btn btn-success input-group-append rename" data-path="/{{ path | join('/') }}">确定</button>
                </div>
            </div>
          </div>
        </div>
        <div id="move" class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
            <div class="modal-content">
              <div class="input-group">
                  <input type="text" class="form-control" placeholder="输入目标文件夹" aria-label="Recipient's username" aria-describedby="basic-addon2">
                  <button class="btn btn-success input-group-append move" data-path="/{{ path | join('/') }}">确定</button>
                </div>
            </div>
          </div>
        </div>
        <div id="showfile" class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
              
            </div>
          </div>
        </div>
        <div class="row">
            <nav class="col-md-8" aria-label="breadcrumb">
              <ol class="breadcrumb">
                {% with %}
                {% for item in path %}
                {% if loop.last %}
                <li class="breadcrumb-item active" aria-current="page">{{ item }}</li>
                {% else %}
                <li class="breadcrumb-item"><a href="/pan?path=/{{ path | slice(loop.length - loop.index + 1) | first | join('/')}}">{{ item }}</a></li>
                {% endif %}
                {% endfor %}
                {% endwith %}
              </ol>
            </nav>
        </div>
        <div class="row">
            <div class="col-md pb-4 table-responsive">
                <table class="table table-hover table-striped" style="background: #f8f9fa;">
                        <thead>
                            <tr>
                                <th scope="col">类型</th>
                                <th scope="col">文件名</th>
                                <th scope="col">类型</th>
                                <th scope="col">创建时间</th>
                                <th scope="col">修改时间</th>
                                <th scope="col">删除</th>
                            </tr>
                        </thead>
                    <tbody>
                        {% for item in files %}
                        <tr>
                            {% if item.content_type == 'd' %}
                            <th scope="row"><a href="/pan?path={{ item.path }}/{{ item.filename }}"><i class="fa fa-folder-o"></i></a></th>
                            <!-- <td>{{ item.filename }}</td> -->
                            <td><button class="btn btn-sm diropt" data-path="{{ item.path }}/{{ item.filename }}" data-name="{{ item.filename }}" data-type="{{ item.content_type }}">{{ item.filename }}</button class="btn"></td>
                            {% else %}
                            <th scope="row"><i class="fa fa-file-o"></i></th>
                            {% if item.file_id %}
                            <td><button class="btn btn-sm fileopt" data-path="{{ item.path }}/{{ item.filename }}" data-id="{{ item.file_id }}" data-name="{{ item.filename }}" data-type="{{ item.content_type }}">{{ item.filename }}</button class="btn"></td>
                            {% else %}
                            <td><button class="btn btn-sm" onclick="location.reload()">{{ item.filename }}[文件上传中...]</button class="btn"></td>
                            {% endif %}
                            {% endif %}
                            <td>{{ item.content_type }}</td>
                            <td><span>{{ item.created_at }}</span></td>
                            <td>{{ item.updated_at }}</td>
                            <td><button class="btn btn-sm delete" data-path="{{ item.path }}/{{ item.filename }}"><i class="fa fa-trash-o"></i></button></td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
<!-- 
            <aside class="col-md-4 blog-sidebar">
                <div class="p-4 mb-3 bg-light rounded">
                    <h4 class="font-italic">用户信息</h4>
                    {% if __user__ %}
                    <p class="mb-0">{{ __user__.name }}</p>
                    <p class="mb-0">{{ __user__.email }}</p>
                    {% else %}
                    <p class="mb-0">用户未登录</p>
                    {% endif %}
                  </div>
            </aside>
 -->
        </div>
    </div>
{% endblock %}

{% block beforebody %}
<script>
    // 新建文件夹
    document.querySelector('#mkdir button.mkdir').addEventListener('click', event => {
        let el = event.target
        let parent = el.dataset["path"]
        let name = el.parentNode.querySelector('input').value
        axios.get('/pan/mkdir/' + name, {
            params: {
                parent: parent,
            }
        })
        .then(function (response) {
            // console.log(response);
            if (response.status === 200) {
                let data = response.data
                if (data['code'] === 0) {
                    console.log('SUCCESS: ' + data['msg'])
                    location.assign('/pan?path=' + data['msg'])
                } else {
                    console.log('FAILED: ' + data['msg'])
                    alert(data['msg'])
                }
            }
        })
        .catch(function (error) {
            console.log(error);
        });
    })
    // 离线下载
    document.querySelector('#offline button.offline').addEventListener('click', event => {
        let el = event.target
        let parent = el.dataset["path"]
        let url = el.parentNode.querySelector('input').value
        axios.get('/pan/offline', {
            params: {
                parent: parent,
                url: url,
            }
        })
        .then(function (response) {
            // console.log(response);
            if (response.status === 200) {
                let data = response.data
                if (data['code'] === 0) {
                    console.log('SUCCESS: ' + data['msg'])
                    location.assign('/pan?path=' + data['msg'])
                } else {
                    console.log('FAILED: ' + data['msg'])
                    alert(data['msg'])
                }
            }
        })
        .catch(function (error) {
            console.log(error);
        });
    })
    // 删除
    document.querySelectorAll('.delete').forEach(el=>{
        el.addEventListener('click', event=>{
            let path = event.target.dataset['path'] ? event.target.dataset['path'] : event.target.parentNode.dataset['path']
            if(confirm('删除路径[' + path + ']')){
                console.log('删除路径[' + path + ']');
                axios.get('/pan/file/delete', {
                  params: {
                    path: path
                  }
                })
                .then(function (response) {
                    // console.log(response);
                    if (response.status === 200) {
                        let data = response.data
                        if (data['code'] === 0) {
                            console.log('SUCCESS: ' + data['msg'])
                            location.assign('/pan?path=' + data['msg'])
                        } else {
                            console.log('FAILED: ' + data['msg'])
                            alert(data['msg'])
                        }
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
            }
        })
    })
    // 上传
    const fileSelect = document.getElementById("fileSelect"),
    fileElem = document.getElementById("fileElem");
    
    fileSelect.addEventListener("click", function (e) {
        console.log('-------上传文件------------')
        if (fileElem) {
            fileElem.click();
        }
    }, false);
    
    function sendFile(){
      let formData = new FormData()
      formData.append("upload", fileElem.files[0])
      formData.append("parent", "/{{ path | join('/') }}")
      url = '/pan/file/upload'
      url = '/pan/file/upload_large'
      url = '/pan/file/upload_tmpfile'
      axios.post(url,formData, {
        'Content-Type': 'multipart/form-data'
      }).
      then(function (response) {
          // console.log(response);
          if (response.status === 200) {
              let data = response.data
              if (data['code'] === 0) {
                  console.log('SUCCESS: ' + data['msg'])
                  location.assign('/pan?path=' + data['msg'])
              } else {
                  console.log('FAILED: ' + data['msg'])
                  alert(data['msg'])
              }
          }
      })
    }
    fileElem.addEventListener('change', sendFile, false)
    // const dropzone = document.getElementById("dropzone");
    fileSelect.ondragover = fileSelect.ondragenter = function(event) {
        event.stopPropagation();
        event.preventDefault();
    }
    // 拖拽文件
    fileSelect.ondrop = function(event) {
        event.stopPropagation();
        event.preventDefault();
        console.log('send file' + event.dataTransfer.files[0])
        sendFile(event.dataTransfer.files[0])
    }
    // 点击文件名,弹出文件操作选项,并位操作选项添加属性
    document.querySelectorAll('.fileopt').forEach(el => {
      el.addEventListener('click', function(event) {
        $('#optfile')[0].querySelector('.download').dataset['path'] = event.target.dataset['id']
        $('#optfile')[0].querySelector('.download').dataset['name'] = event.target.dataset['name']
        $('#optfile')[0].querySelector('.showfile').dataset['path'] = event.target.dataset['id']
        $('#optfile')[0].querySelector('.showfile').dataset['type'] = event.target.dataset['type']
        $('#optfile')[0].querySelector('.move').dataset['path'] = event.target.dataset['path']
        $('#optfile')[0].querySelector('.rename').dataset['path'] = event.target.dataset['path']
        // $('#optfile').collapse('hide')
        $('#optfile').collapse('show')
      })
    })
    // 文件操作列表,清理属性
    $('#optfile').on('hidden.bs.collapse', function () {
      $('#optfile')[0].querySelector('.showfile').dataset['path'] = ''
    })
    // 关闭文件操作
    document.querySelector('main').addEventListener('click', ()=>{
      $('#optfile').collapse('hide')
      $('#optdir').collapse('hide')
    }, false)
    $('#showfile').on('hidden.bs.modal', function(event) {
        document.querySelector('#showfile .modal-content').innerHTML = ''
    })
    // 下载文件
    document.querySelectorAll('#optfile .download').forEach(el => {
      el.addEventListener('click', function(event) {
        let link = document.createElement('a');
        //设置下载的文件名
        link.download = event.target.dataset['name'];
        console.log(link.download)
        link.style.display = 'none';
        //设置下载路径
        link.href = '{{ dfsurl }}/' + el.dataset['path'];
        //触发点击
        document.body.appendChild(link);
        link.click();
        //移除节点
        document.body.removeChild(link);
      })
    })
    // 预览文件
    document.querySelectorAll('#optfile .showfile').forEach(el => {
      el.addEventListener('click', function(event) {
        if (event.target.dataset['type'].startsWith('image')) {
          let img = document.createElement('img')
          img.src = '{{ dfsurl }}/' + el.dataset['path']
          img.style = 'object-fit: contain;'
          document.querySelector('#showfile .modal-content').innerHTML = ''
          document.querySelector('#showfile .modal-content').append(img)
          $('#showfile').modal('show')
        }
        if (event.target.dataset['type'].startsWith('video')) {
          let video = document.createElement('video')
          video.src = '{{ dfsurl }}/' + el.dataset['path']
          video.controls="controls"
          video.style = 'object-fit: contain;'
          document.querySelector('#showfile .modal-content').innerHTML = ''
          document.querySelector('#showfile .modal-content').append(video)
          $('#showfile').modal('show')
        }
      })
    })
    // 移动
    document.querySelectorAll('#optfile .move').forEach(el => {
      el.addEventListener('click', function(event) {
        let fullpath = event.target.dataset['path']
        $('#move')[0].querySelector('button.move').dataset['path'] = fullpath
        $('#move').modal('show')
      })
    })
    // 重命名
    document.querySelectorAll('#optfile .rename').forEach(el => {
      el.addEventListener('click', function(event) {
        let fullpath = event.target.dataset['path']
        $('#rename')[0].querySelector('button.rename').dataset['path'] = fullpath
        $('#rename').modal('show')
      })
    })
    /*********************************************/
    // 移动
    document.querySelector('#move button.move').addEventListener('click', event => {
        let el = event.target
        let fullpath = el.dataset["path"]
        let newpath = el.parentNode.querySelector('input').value
        axios.get('/pan/move', {
            params: {
                fullpath: fullpath,
                newpath: newpath,
            }
        })
        .then(function (response) {
            // console.log(response);
            if (response.status === 200) {
                let data = response.data
                if (data['code'] === 0) {
                    console.log('SUCCESS: ' + data['msg'])
                    location.assign('/pan?path=' + data['msg'])
                } else {
                    console.log('FAILED: ' + data['msg'])
                    alert(data['msg'])
                }
            }
        })
        .catch(function (error) {
            console.log(error);
        });
    })
    // 重命名
    document.querySelector('#rename button.rename').addEventListener('click', event => {
        let el = event.target
        let fullpath = el.dataset["path"]
        let newname = el.parentNode.querySelector('input').value
        axios.get('/pan/rename', {
            params: {
                fullpath: fullpath,
                newname: newname,
            }
        })
        .then(function (response) {
            // console.log(response);
            if (response.status === 200) {
                let data = response.data
                if (data['code'] === 0) {
                    console.log('SUCCESS: ' + data['msg'])
                    location.assign('/pan?path=' + data['msg'])
                } else {
                    console.log('FAILED: ' + data['msg'])
                    alert(data['msg'])
                }
            }
        })
        .catch(function (error) {
            console.log(error);
        });
    })
    /********************************************************************/
    // 文件夹操作
    document.querySelectorAll('.diropt').forEach(el => {
      el.addEventListener('click', function(event) {
        $('#optdir')[0].querySelector('.move').dataset['path'] = event.target.dataset['path']
        $('#optdir')[0].querySelector('.rename').dataset['path'] = event.target.dataset['path']
        $('#optdir').collapse('show')
      })
    })
    // 移动
    document.querySelectorAll('#optdir .move').forEach(el => {
      el.addEventListener('click', function(event) {
        let fullpath = event.target.dataset['path']
        $('#move')[0].querySelector('button.move').dataset['path'] = fullpath
        $('#move').modal('show')
      })
    })
    // 重命名
    document.querySelectorAll('#optdir .rename').forEach(el => {
      el.addEventListener('click', function(event) {
        let fullpath = event.target.dataset['path']
        $('#rename')[0].querySelector('button.rename').dataset['path'] = fullpath
        $('#rename').modal('show')
      })
    })
</script>
{% endblock %}